package captcha

import (
	"github.com/gogf/gf/v2/database/gredis"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/mojocn/base64Captcha"
	"time"
)

var ctx = gctx.New()
var store base64Captcha.Store
var driver base64Captcha.Driver = base64Captcha.DefaultDriverDigit

// Generate 生成验证码
func Generate() (string, string, error) {
	_, ok := gredis.GetConfig()
	if store == nil {
		if ok {
			store = new(RedisStore)
		} else {
			store = base64Captcha.DefaultMemStore
		}
	}

	c := base64Captcha.NewCaptcha(driver, store)
	// 获取
	id, b64s, _, err := c.Generate()
	return id, b64s, err
}

// Verify 验证验证码
func Verify(id string, val string) bool {
	if store == nil || id == "" || val == "" {
		return false
	}
	// 同时清理掉这个图片
	return store.Verify(id, val, true)
}

type RedisStore struct {
}

const CAPTCHA = "zuhao_secure_rsa.private:captcha:"

// Set 实现设置captcha的方法
func (r RedisStore) Set(id string, value string) error {
	//time.Minute*2：有效时间2分钟
	err := g.Redis().SetEX(ctx, CAPTCHA+id, value, int64(time.Minute*2))
	if err != nil {
		return err
	}
	return nil
}

// Get 实现获取captcha的方法
func (r RedisStore) Get(id string, clear bool) string {
	key := CAPTCHA + id
	val, err := g.Redis().Get(ctx, key)
	if err != nil {
		return ""
	}
	if clear {
		//clear为true，验证通过，删除这个验证码
		g.Redis().Del(ctx, key)
	}
	return val.String()
}

// Verify 实现验证captcha的方法
func (r RedisStore) Verify(id, answer string, clear bool) bool {
	return r.Get(id, clear) == answer
}
